﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Threading;
using NetCore.Log;
using NetCore.WS;

namespace NetCore
{
    /// <summary>
    /// 任务 启动类
    /// </summary>
    public class TaskHelper
    {
        private static List<TaskModel> _taskModels = new List<TaskModel>();
        /// <summary>
        /// 任务管理
        /// </summary>
        public static List<TaskModel> TaskModels { get => _taskModels; set => _taskModels = value; }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="title"></param>
        /// <param name="userid"></param>
        /// <param name="userToken"></param>
        /// <param name="func"></param>
        public static void TaskStart(string title,string userid,string userToken,Func<TaskModel, bool> func)
        {
            var taskModel = new TaskModel();
            taskModel.TaskName = title;
            taskModel.TaskId = MyGenerateHelper.GenerateOrder(5);
            taskModel.TaskToken= new CancellationTokenSource();
            taskModel.UserNo = userid;
            taskModel.UserToken = userToken;
            taskModel.CurrentTask= Task.Factory.StartNew(() => {
                taskModel.StartDate = DateTime.Now;
                taskModel.IsOpen = true;
                int milliStart = Environment.TickCount;
                taskModel.ExcuteFunc = func;
                try
                {
                    taskModel.IsSuccess = taskModel.ExcuteFunc(taskModel);
                    taskModel.Message = "成功"; 
                }
                catch (Exception ex)
                {
                    taskModel.Message ="任务执行失败,原因："+ ex.Message;
                    taskModel.IsSuccess = false;
                }
                if (taskModel.TaskToken.Token.IsCancellationRequested)
                {
                    taskModel.IsSuccess = false;
                    taskModel.Message = "任务被强行终止";
                }
                int milliEnd = Environment.TickCount;
                taskModel.EndDate = DateTime.Now;
                taskModel .ExcuteTime=  TimeSpan.FromMilliseconds(milliEnd - milliStart).TotalMilliseconds;
                taskModel.IsOpen = false;
                TaskModels.Remove(taskModel);
                LogHelper.Info(taskModel.TaskName, taskModel.ToJson());
                SendResultMessage(taskModel.UserNo,taskModel.UserToken, title + taskModel.Message);
            },TaskCreationOptions.LongRunning);
            TaskModels.Add(taskModel);
          
          
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public static bool Stop(string taskId,ref string strError)
        {
            if (string.IsNullOrWhiteSpace(taskId))
            {
                strError = "请输入需要终止的任务id";
                return false;
            }
            var task= TaskModels.Where(x => x.TaskId == taskId).FirstOrDefault();
            if (task == null|| !task.IsOpen)
            {
                strError = "任务不存在或者已关闭";
                return false;
            }
            
            task.TaskToken.Cancel();
            task.Message = "任务被强行终止";
           
           // LogHelper.Info(task.TaskName, task.ToJson());
            //TaskModels.Remove(task);
            return true;
        }

        /// <summary>
        /// 发送任务结果
        /// </summary>
        /// <param name="userno"></param>
        /// <param name="userToken"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static bool SendResultMessage(string userno,string userToken, string message)
        {
          var socketMessage=  new SocketMessageModel
            {
                SenderId = "Service",
                SenderName = "系统",
                ReceiverId = userno,
                Content = message
            };
            string strResult = "";
           return SendHttpHelper.SendWebClient(ApplicationEnvironments.Site.SendMessageUrl, socketMessage.ToJson(), userToken, ref strResult);
       
        }

    }

    /// <summary>
    /// 任务
    /// </summary>
    public class TaskModel
    {
        /// <summary>
        /// 任务编码
        /// </summary>
        public string TaskId { get; set; }
        /// <summary>
        /// 任务名称
        /// </summary>
        public string TaskName { get; set; }

        /// <summary>
        /// 执行时间
        /// </summary>
        public double ExcuteTime { get; set; }
        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime EndDate { get; set; }

        public bool IsOpen { get; set; }
        [JsonIgnore]
        /// <summary>
        /// 执行方法 返回true or false
        /// </summary>
        public Func<TaskModel, bool> ExcuteFunc { get; set; }

        [JsonIgnore]
        public Task CurrentTask { get; set; }

        /// <summary>
        /// 取消标志
        /// </summary>
        public CancellationTokenSource TaskToken { get; set; }

        /// <summary>
        /// 是否执行成功
        /// </summary>
        public bool IsSuccess { get; set; }

        /// <summary>
        /// 输出消息
        /// </summary>
        public string Message { get; set; }

        public string UserNo { get; set; }

        public string UserToken { get; set; }
    }
}
